package com.lcn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcn.base.BaseInfoProperties;
import com.lcn.mapper.ChatMessageMapper;
import com.lcn.pojo.ChatMessage;
import com.lcn.pojo.netty.ChatMsg;
import com.lcn.service.ChatMessageService;
import com.lcn.utils.PagedGridResult;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatMessageServiceImpl extends BaseInfoProperties implements ChatMessageService {

    @Resource
    private ChatMessageMapper chatMessageMapper;

    /**
     * 将消息保存到数据库
     *
     * @param chatMsg
     */
    @Override
    public void saveChatMessage(ChatMsg chatMsg) {
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMsg, chatMessage);
        chatMessage.setId(chatMsg.getMsgId()); // 雪花算法id，在上一级中就已经设置好了
        chatMessageMapper.insert(chatMessage);
        // 未读累加
        String receiverId = chatMsg.getReceiverId();
        String senderId = chatMsg.getSenderId();
        redis.incrementHash(CHAT_MSG_LIST + ":" + receiverId, senderId, 1);
    }

    /**
     * 分页查询历史聊天记录
     *
     * @param senderId
     * @param receiverId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PagedGridResult list(String senderId, String receiverId, Integer page, Integer pageSize) {
        Page<ChatMessage> chatMessagePage = new Page<>(page, pageSize);
        // 双向查询
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<ChatMessage>()
                .or(qw -> qw.eq("sender_id", senderId).eq("receiver_id", receiverId))
                .or(qw -> qw.eq("sender_id", receiverId).eq("receiver_id", senderId))
                .orderByDesc("chat_time"); // 按时间倒序查，查最新的
        chatMessageMapper.selectPage(chatMessagePage, queryWrapper);
        List<ChatMessage> records = chatMessagePage.getRecords();
        // 上面按时间倒序是按分页查的最新的，现在是按最新的数据再次进行排序，让聊天记录在下方
        List<ChatMessage> result = records.stream().sorted(
                Comparator.comparing(ChatMessage::getChatTime)
        ).collect(Collectors.toList());
        chatMessagePage.setRecords(result);
        return setterPagedGridPlus(chatMessagePage);
    }

}
